package com.xiaobaili.controller;

import com.xiaobaili.config.WeiXinConfigProperties;
import com.xiaobaili.domain.entity.MessageTextEntity;
import com.xiaobaili.utils.SignatureUtils;
import com.xiaobaili.utils.XmlUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@CrossOrigin("*")
@RestController
@RequestMapping("/api/v1/weixin/portal/")
public class WeiXinController {

    private final WeiXinConfigProperties weiXinConfigProperties;

    // 通过构造函数注入 WeiXinConfigProperties
    @Autowired
    public WeiXinController(WeiXinConfigProperties weiXinConfigProperties) {
        this.weiXinConfigProperties = weiXinConfigProperties;
    }

    @PostMapping(value = "receive", produces = "text/plain;charset=utf-8")
    public String validate(@RequestBody String requestBody,
                           @RequestParam("openid") String openid,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           HttpServletRequest request) throws Exception {
        try {
            log.info("接收到微信消息，参数：openid:{},signature:{},timestamp:{},nonce:{},requestBody:{}", openid, signature, timestamp, nonce, requestBody);
            if (StringUtils.isAnyBlank(signature, timestamp, nonce, requestBody)) {
                throw new IllegalArgumentException("请求参数非法，请核实!");
            }
            if (!SignatureUtils.checkSignature(signature, timestamp, nonce, weiXinConfigProperties.getToken())) {
                throw new IllegalArgumentException("验签不合法!");
            }
            MessageTextEntity messageText = XmlUtil.xmlToBean(requestBody, MessageTextEntity.class);
            return buildMessageTextEntity(openid, "你好" + messageText.getContent());
        } catch (Exception e) {
            log.info("微信公众号接受信息异常，参数：openid：{},signature：{},timestamp：{},nonce：{},requestBody：{},", openid, signature, timestamp, nonce, requestBody);
            return null;
        }
    }

    private String buildMessageTextEntity(String openid, String content) {
        MessageTextEntity res = new MessageTextEntity();
        // 公众号分配的ID
        res.setFromUserName(weiXinConfigProperties.getOriginalId());
        res.setToUserName(openid);
        res.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000L));
        res.setMsgType("text");
        res.setContent(content);
        return XmlUtil.beanToXml(res);
    }
}

